package com.speedchina.framework.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author xz
 * 获取spring容器的上下文，拿到容器中的bean
 *
 */
@Component
public class ApplicationContextHolder implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationContextHolder.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 根据applicationContext上下文对象来获取bean
     * @param tClass 传入类的字节码对象
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> tClass) {
        try {
            return applicationContext.getBean(tClass);
        }catch (BeansException e) {}
        return null;
    }

    /**
     * 根据applicationContext上下文对象来获取bean
     * @param tClass 出入bean的name获取bean
     * @param <T>
     * @return
     */
    public static <T> T getBean(String tClass) {
        return ((T) applicationContext.getBean(tClass));
    }

}
